using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Net.Mail;
using Toenda.Rails.Data;
using Toenda.Rails.DataContainer;
using Toenda.TFL.Base;
using Toenda.TFL.Data;

namespace Toenda.Rails {
	namespace Data {
		/// <summary>
		/// Class DBAccount
		/// </summary>
		public class DBAccount : DBClient {
			// ---------------------------------------------------------
			// CONSTRUCTORS
			// ---------------------------------------------------------

			/// <summary>
			/// Default constructor
			/// </summary>
			public DBAccount() {
			}

			// ---------------------------------------------------------
			// PUBLIC MEMBERS
			// ---------------------------------------------------------

			/// <summary>
			/// Get a list of all online user
			/// </summary>
			/// <returns></returns>
			public List<Account> GetAllOnlineUser() {
				List<Account> list = new List<Account>();
				StringBuilder str = new StringBuilder();

				str.Append("SELECT s.date as login_time, u.*, g.*");
				str.Append(" FROM tbl_session AS s");
				str.Append(" INNER JOIN tbl_user AS u");
				str.Append(" ON s.user_pkid = u.pkid");
				str.Append(" INNER JOIN tbl_usergroup AS g");
				str.Append(" ON u.group_pkid = g.pkid");
				str.Append(" ORDER BY s.date");

				DataSet data = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(data.Tables[0].Rows.Count > 0) {
					DataTableReader reader = data.CreateDataReader();

					while(reader.Read()) {
						Account acc = this.FillAccountFromTableReader(reader, 0);
						acc.LoginTime = reader.GetDateTime(reader.GetOrdinal("login_time"));

						list.Add(acc);
					}
				}

				return list;
			}

			/// <summary>
			/// Get a account
			/// </summary>
			/// <param name="id">The id (userid, sessionid, username)</param>
			/// <param name="type">The type to get the account</param>
			/// <returns></returns>
			public Account GetAccount(string id, GetAccountType type) {
				return this.GetAccount(id, (int)type);
			}

			/// <summary>
			/// Get a account
			/// </summary>
			/// <param name="UniqueID"></param>
			/// <param name="Nothing"></param>
			/// <returns></returns>
			public Account GetAccount(string UniqueID, int Nothing) {
				DataSet dsData = new DataSet();
				DataTableReader oDT = null;
				Account oAcc = new Account();

				switch(Nothing) {
					case 0:
						string strTemp = base.GetUserIDBySessionID(UniqueID);
						if(strTemp != "")
							dsData = base.GetUser(strTemp);
						break;

					case 1:
						dsData = base.GetUser(UniqueID);
						break;

					case 2:
						dsData = base.GetUserByUsername(UniqueID);
						break;
				}

				if(dsData.Tables[0].Rows.Count > 0) {
					oDT = dsData.CreateDataReader();
					oDT.Read();

					oAcc = this.FillAccountFromTableReader(oDT, 0);

					DataSet data = base.GetUserSettingsByUserID(oAcc.ID);

					if(data.Tables[0].Rows.Count > 0) {
						oDT = data.CreateDataReader();
						oDT.Read();
					}
					else {
						oDT = null;
					}

					oAcc.AccountSettings = this._FillAccountSettingsFromTableReader(oDT, oAcc.ID);
				}

				return oAcc;
			}

			/// <summary>
			/// Get a list of all users
			/// </summary>
			/// <param name="Order"></param>
			/// <param name="ListAttribute"></param>
			/// <returns></returns>
			public ArrayList GetAccounts(OrderUserBy Order, UserListAttribute ListAttribute) {
				ArrayList arr = new ArrayList();
				StringBuilder str = new StringBuilder();

				if(Order == OrderUserBy.Undefined) {
					Order = OrderUserBy.RegisterDateASC;
				}

				if(ListAttribute == UserListAttribute.Undefined) {
					ListAttribute = UserListAttribute.All;
				}

				str.Append("SELECT *");
				str.Append(" FROM [dbo].[tbl_user]");
				str.Append(" INNER JOIN [dbo].[tbl_usergroup]");
				str.Append(" ON [tbl_user].[group_pkid] = [tbl_usergroup].[pkid]");

				switch(ListAttribute) {
					case UserListAttribute.AllEnabled:
						str.Append(" WHERE enabled = 1");
						break;

					case UserListAttribute.AllDisabled:
						str.Append(" WHERE enabled = 0");
						break;

					case UserListAttribute.AllProEnabled:
						str.Append(" WHERE NOT (pro_start_date IS NULL)");
						break;

					case UserListAttribute.AllProEnabledExpectOfAdmin:
						str.Append(" WHERE NOT (pro_start_date IS NULL) AND NOT (username = 'admin')");
						break;

					case UserListAttribute.AllProDisabled:
						str.Append(" WHERE (pro_start_date IS NULL)");
						break;

					case UserListAttribute.NewestFromLast30Days:
						str.Append(" WHERE dateadd(w, 30, [register_date]) > getdate()");
						break;

					case UserListAttribute.All:
						str.Append(" WHERE enabled = 0 OR enabled = 1");
						break;

					case UserListAttribute.UpgradeInWorkPlusEnabled:
						str.Append(" WHERE upgrade_in_work = 1 AND enabled = 1");
						break;

					case UserListAttribute.UpgradeNotInWorkPlusEnabled:
						str.Append(" WHERE upgrade_in_work = 0 AND enabled = 1");
						break;
				}

				switch(Order) {
					case OrderUserBy.RegisterDateASC:
						str.Append(" ORDER BY register_date ASC");
						break;

					case OrderUserBy.RegisterDateDESC:
						str.Append(" ORDER BY register_date DESC");
						break;
				}

				DataSet dsData = base.DBBaseClass.ExecuteQuery(str.ToString());
				DataTableReader tr = dsData.CreateDataReader();
				DataSet data = null;
				DataTableReader tr2 = null;
				long lR = 1;

				while(tr.Read()) {
					Account acc = new Account();
					acc = this.FillAccountFromTableReader(tr, lR);
					arr.Add(acc);

					// settings
					data = base.GetUserSettingsByUserID(acc.ID);

					if(data.Tables[0].Rows.Count > 0) {
						tr2 = data.CreateDataReader();
						tr2.Read();
					}
					else {
						tr2 = null;
					}

					acc.AccountSettings = this._FillAccountSettingsFromTableReader(tr, acc.ID);

					lR++;
				}

				return arr;
			}

			/// <summary>
			/// Delete a user
			/// </summary>
			/// <param name="ID"></param>
			public void DeleteUser(string ID) {
				StringBuilder str = new StringBuilder();

				// delete stuff
				str.Remove(0, str.Length);
				str.Append("DELETE FROM [dbo].[tbl_images]");
				str.Append(" WHERE user_pkid = '" + ID + "'");

				base.DBBaseClass.ExecuteNonQuery(str.ToString());

				str.Remove(0, str.Length);
				str.Append("DELETE FROM [dbo].[tbl_user_settings]");
				str.Append(" WHERE user_pkid = '" + ID + "'");

				base.DBBaseClass.ExecuteNonQuery(str.ToString());

				str.Remove(0, str.Length);
				str.Append("DELETE FROM [dbo].[tbl_sets]");
				str.Append(" WHERE user_pkid = '" + ID + "'");

				base.DBBaseClass.ExecuteNonQuery(str.ToString());

				// delete user
				str.Remove(0, str.Length);
				str.Append("DELETE FROM [dbo].[tbl_user]");
				str.Append(" WHERE pkid = '" + ID + "'");

				int iRes = base.DBBaseClass.ExecuteNonQuery(str.ToString());
			}

			/// <summary>
			/// Login
			/// </summary>
			/// <param name="Username">The username</param>
			/// <param name="Password">The password</param>
			/// <param name="Session"></param>
			/// <param name="userID"></param>
			/// <returns></returns>
			public ErrorType Login(string Username, string Password, ref string Session, ref string userID) {
				string strUID;
				string strSID = "";
				byte[] byBuffer = new byte[16];
				byte[] byBuffer2 = new byte[16];
				bool bCheck = true;
				ErrorType err = new ErrorType();
				DataTableReader oDTR = null;
				MD5CryptoServiceProvider oMD5CSP = new MD5CryptoServiceProvider();
				StreamWriter oSW = new StreamWriter(new CryptoStream(Stream.Null, oMD5CSP, CryptoStreamMode.Write));

				oSW.Write(Password);
				oSW.Flush();
				oSW.Close();

				StringBuilder str = new StringBuilder();

				str.Append("SELECT usr.*");
				str.Append(" FROM [dbo].[tbl_user] AS usr");
				str.Append(" INNER JOIN [dbo].[tbl_usergroup] AS grp");
				str.Append(" ON usr.group_pkid = grp.pkid");
				//str.Append(" INNER JOIN [dbo].[tbl_teams] AS team");
				//str.Append(" ON usr.team_pkid = team.pkid");
				str.Append(" WHERE usr.username = '" + Username + "'");
				//str.Append(" AND team.name = '" + Team + "'");
				str.Append(" AND usr.enabled = 1");

				DataSet dsData = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(dsData.Tables[0].Rows.Count > 0) {
					oDTR = dsData.CreateDataReader();
					oDTR.Read();

					byBuffer2 = oMD5CSP.Hash;

					oDTR.GetBytes(oDTR.GetOrdinal("password"), 0, byBuffer, 0, 16);

					for(int i = 0; i < byBuffer.Length; i++) {
						if(byBuffer[i] != byBuffer2[i]) bCheck = false;
					}

					//bCheck = true;

					if(bCheck) {
						strUID = oDTR["pkid"].ToString();
						strSID = Guid.NewGuid().ToString();

						str.Remove(0, str.Length);
						str.Append("INSERT INTO [dbo].[tbl_session]");
						str.Append(" ([pkid], [user_pkid], [date])");
						str.Append(" VALUES");
						str.Append(" ('" + strSID + "', '" + strUID + "', getdate())");

						base.DBBaseClass.ExecuteNonQuery(str.ToString());

						Session = strSID;
						userID = strUID;

						err = ErrorType.NoError;
					}
					else {
						err = ErrorType.IncorrectPassword;
					}
				}
				else {
					str.Remove(0, str.Length);
					str.Append("SELECT * FROM [dbo].[tbl_user]");
					str.Append(" WHERE [tbl_user].[username] = '" + Username + "'");

					dsData = base.DBBaseClass.ExecuteQuery(str.ToString());

					if(dsData.Tables[0].Rows.Count > 0) {
						str.Remove(0, str.Length);
						str.Append("SELECT * FROM [dbo].[tbl_user]");
						str.Append(" WHERE [tbl_user].[username] = '" + Username + "'");
						str.Append(" AND [tbl_user].[enabled] = 0");

						dsData = base.DBBaseClass.ExecuteQuery(str.ToString());

						if(dsData.Tables[0].Rows.Count > 0) {
							err = ErrorType.UsernameDisabled;
						}
						else {
							err = ErrorType.DefaultLoginError;
						}
					}
					else {
						err = ErrorType.IncorrectUsername;
					}
				}

				return err;
			}

			/// <summary>
			/// Logout
			/// </summary>
			/// <param name="SessionID"></param>
			public void Logout(string SessionID) {
				string strSQLString = "DELETE FROM [dbo].[tbl_session]"
					+ " WHERE [pkid] = '" + SessionID + "'";

				int nResult = base.DBBaseClass.ExecuteNonQuery(strSQLString);
			}

			/// <summary>
			/// Save user account settings
			/// </summary>
			/// <param name="accs"></param>
			public void SaveAccountSettings(AccountSettings accs) {
				DataSet data = base.GetUserSettingsByUserID(accs.UserID);
				DataRow row;
				bool add = false;

				if(data.Tables[0].Rows.Count > 0) {
					row = data.Tables[0].Rows[0];
				}
				else {
					row = data.Tables[0].NewRow();
					add = true;

					accs.ID = Guid.NewGuid().ToString();

					row["pkid"] = accs.ID;
					row["user_pkid"] = accs.UserID;
				}

				row["imagelist_layout"] = (int)accs.ImageListLayout;

				if(add) {
					data.Tables[0].Rows.Add(row);
				}

				int iResult = base.DBBaseClass.ExecuteUpdate(data, "tbl_user_settings");
			}

			/// <summary>
			/// Save user account
			/// </summary>
			/// <param name="acc"></param>
			/// <param name="Password"></param>
			public void SaveAccount(Account acc, string Password) {
				DataSet data = base.GetUserWithoutGroup(acc.ID);
				DataRow row = data.Tables[0].Rows[0];

				row["username"] = acc.Username;
				row["firstname"] = acc.Firstname + "";
				row["lastname"] = acc.Lastname + "";
				row["email"] = acc.Email + "";
				row["desc"] = acc.Description + "";
				row["webpage"] = acc.Webpage + "";
				row["webpage_name"] = acc.WebpageName + "";
				row["location"] = acc.Location + "";
				row["country"] = acc.Country + "";
				row["enabled"] = acc.Enabled;
				row["language"] = acc.Language + "";

				if(acc.Birthday != null
				&& acc.Birthday.ToShortDateString() != "01.01.0001"
				&& acc.Birthday.ToShortDateString() != "01.01.1753"
				&& acc.Birthday.ToShortDateString() != "01.01.1799"
				&& acc.Birthday.Year > 1901) {
					row["birth"] = acc.Birthday;
				}

				if(acc.Avatar != null)
					row["avatar"] = acc.Avatar;

				if(Password.Trim() != "") {
					MD5CryptoServiceProvider oMD5CSP = new MD5CryptoServiceProvider();
					StreamWriter oSW = new StreamWriter(new CryptoStream(Stream.Null, oMD5CSP, CryptoStreamMode.Write));

					oSW.Write(Password);
					oSW.Flush();
					oSW.Close();

					row["password"] = oMD5CSP.Hash;
				}

				int iResult = base.DBBaseClass.ExecuteUpdate(data, "tbl_user");
			}

			/// <summary>
			/// Create a new account
			/// </summary>
			/// <param name="acc"></param>
			/// <param name="Password"></param>
			public void CreateNewAccount(Account acc, string Password) {
				DataSet data = base.GetUserWithoutGroup(acc.ID);
				DataRow row = data.Tables[0].NewRow();

				row["pkid"] = acc.ID;
				row["group_pkid"] = "178efc30-5a67-472f-a1e2-e0f0f97f1c97";
				row["username"] = acc.Username;
				row["firstname"] = acc.Firstname + "";
				row["lastname"] = acc.Lastname + "";
				row["email"] = acc.Email + "";
				row["desc"] = acc.Description + "";
				row["webpage"] = acc.Webpage + "";
				row["webpage_name"] = acc.WebpageName + "";
				row["location"] = acc.Location + "";
				row["country"] = acc.Country + "";
				row["language"] = acc.Language + "";

				row["enabled"] = 0;
				row["register_date"] = DateTime.Now;

				if(acc.Birthday != null
				&& acc.Birthday.ToShortDateString() != "01.01.0001"
				&& acc.Birthday.ToShortDateString() != "01.01.1753"
				&& acc.Birthday.ToShortDateString() != "01.01.1799"
				&& acc.Birthday.Year > 1901) {
					row["birth"] = acc.Birthday;
				}

				/*
				drData["zipcode"] = acc.Zipcode + "";
				drData["street"] = acc.Street + "";
				drData["state"] = acc.State + "";
				*/

				if(Password.Trim() != "") {
					MD5CryptoServiceProvider oMD5CSP = new MD5CryptoServiceProvider();
					StreamWriter oSW = new StreamWriter(new CryptoStream(Stream.Null, oMD5CSP, CryptoStreamMode.Write));

					oSW.Write(Password);
					oSW.Flush();
					oSW.Close();

					row["password"] = oMD5CSP.Hash;
				}

				data.Tables[0].Rows.Add(row);

				int iResult = base.DBBaseClass.ExecuteUpdate(data, "tbl_user");
			}

			/// <summary>
			/// Check if a username exists
			/// </summary>
			/// <param name="Username"></param>
			/// <returns></returns>
			public bool CheckUsernameExist(string Username) {
				StringBuilder str = new StringBuilder();

				str.Append("SELECT Username FROM [dbo].[tbl_user]");
				str.Append(" WHERE Username = '" + Username + "'");

				DataSet dsData = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(dsData.Tables[0].Rows.Count == 0)
					return false;
				else
					return true;
			}

			/// <summary>
			/// Check if a session exist
			/// </summary>
			/// <param name="SessionID"></param>
			/// <returns></returns>
			public bool CheckSessionExist(string SessionID) {
				StringBuilder str = new StringBuilder();

				str.Append("SELECT * FROM [dbo].[tbl_session]");
				str.Append(" WHERE [pkid] = '" + SessionID + "'");

				DataSet dsData = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(dsData.Tables[0].Rows.Count > 0) {
					return true;
				}
				else {
					return false;
				}
			}

			/// <summary>
			/// Enable a user
			/// </summary>
			/// <param name="ID"></param>
			public void EnableUser(string ID) {
				Account acc = GetAccount(ID, 1);
				StringBuilder str = new StringBuilder();

				str.Append("UPDATE [dbo].[tbl_user]");
				str.Append(" SET [enabled] = " + (acc.Enabled ? 0 : 1) + "");
				str.Append(" WHERE [pkid] = '" + ID + "'");

				int iRes = base.DBBaseClass.ExecuteNonQuery(str.ToString());
			}

			/// <summary>
			/// Enable a user
			/// </summary>
			/// <param name="ID"></param>
			public void EnableAdmin(string ID) {
				Account acc = GetAccount(ID, 1);
				StringBuilder str = new StringBuilder();

				str.Append("UPDATE [dbo].[tbl_user]");
				str.Append(" SET [group_pkid] = '" + (acc.IsAdmin ? "178efc30-5a67-472f-a1e2-e0f0f97f1c97" : "0fcb1bec-b966-480d-b9cc-855955c528d0") + "'");
				str.Append(" WHERE [pkid] = '" + ID + "'");

				int iRes = base.DBBaseClass.ExecuteNonQuery(str.ToString());
			}

			/// <summary>
			/// Enable a user
			/// </summary>
			/// <param name="ID"></param>
			public void DeleteAvatar(string ID) {
				StringBuilder str = new StringBuilder();

				str.Append("UPDATE [dbo].[tbl_user]");
				str.Append(" SET [avatar] = NULL");
				str.Append(" WHERE [pkid] = '" + ID + "'");

				int iRes = base.DBBaseClass.ExecuteNonQuery(str.ToString());
			}

			/// <summary>
			/// Retrieve a new passwort to the email adress
			/// </summary>
			/// <param name="username"></param>
			/// <param name="email"></param>
			/// <param name="firstname">The firstname as ref to get it.</param>
			/// <param name="lastname">The lastname as ref to get it.</param>
			/// <returns>The admin email</returns>
			public string RetrieveNewPassword(string username, ref string email, ref string firstname, ref string lastname) {
				StringBuilder str = new StringBuilder();

				str.Append("SELECT pkid, email, firstname, lastname");
				str.Append(" FROM [dbo].[tbl_user]");
				str.Append(" WHERE email = '" + email + "'");
				str.Append(" AND username = '" + username + "'");
				str.Append(" AND enabled = 1");

				DataSet dsData = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(dsData.Tables[0].Rows.Count > 0) {
					DataTableReader drData = dsData.CreateDataReader();
					drData.Read();

					DataSet dsUData = base.GetUserWithoutGroup(drData["pkid"].ToString());
					DataRow drUData = dsUData.Tables[0].Rows[0];

					MD5CryptoServiceProvider oMD5CSP = new MD5CryptoServiceProvider();
					StreamWriter oSW = new StreamWriter(new CryptoStream(Stream.Null, oMD5CSP, CryptoStreamMode.Write));
					Random rand = new Random();
					string strPassword = String.Format("{0:x8}", rand.Next());

					oSW.Write(strPassword);
					oSW.Flush();
					oSW.Close();

					drUData["password"] = oMD5CSP.Hash;

					int iResult = base.DBBaseClass.ExecuteUpdate(dsUData, "tbl_user");

					email = drData["email"].ToString();

					return strPassword;
				}
				else {
					return "";
				}
			}

			/// <summary>
			/// Fill a account from table reader
			/// </summary>
			/// <param name="oDT"></param>
			/// <param name="Ranking"></param>
			/// <returns></returns>
			public Account FillAccountFromTableReader(DataTableReader reader, long Ranking) {
				Account acc = new Account();

				acc.Ranking = Ranking;
				acc.UserID = reader["pkid"].ToString();
				acc.Username = reader["username"].ToString();
				acc.Email = reader["email"].ToString();
				acc.Firstname = reader["firstname"].ToString();
				acc.Lastname = reader["lastname"].ToString();
				acc.Enabled = reader.GetBoolean(reader.GetOrdinal("enabled"));

				if(!reader.IsDBNull(reader.GetOrdinal("birth"))) {
					acc.Birthday = reader.GetDateTime(reader.GetOrdinal("birth"));
				}

				if(!reader.IsDBNull(reader.GetOrdinal("pro_start_date"))) {
					acc.ProStartDate = reader.GetDateTime(reader.GetOrdinal("pro_start_date"));
				}
				
				acc.RegisterDate = reader.GetDateTime(reader.GetOrdinal("register_date"));
				acc.Description = reader["desc"].ToString();
				acc.Webpage = reader["webpage"].ToString();
				acc.WebpageName = reader["webpage_name"].ToString();
				acc.Location = reader["location"].ToString();
				acc.Country = reader["country"].ToString();

				acc.UsergroupID = reader["group_pkid"].ToString();
				acc.UsergroupName = reader["name"].ToString();
				acc.MaxStorageMB = reader.GetInt32(reader.GetOrdinal("max_storage_mb"));
				acc.Type = reader.GetInt32(reader.GetOrdinal("type"));

				if(!reader.IsDBNull(reader.GetOrdinal("pro_duration"))) {
					acc.ProDuration = reader.GetInt32(reader.GetOrdinal("pro_duration"));
				}

				if(!reader.IsDBNull(reader.GetOrdinal("avatar"))) {
					acc.Avatar = reader["avatar"].ToString();
				}

				acc.UpgradeIsInWork = reader.GetBoolean(reader.GetOrdinal("upgrade_in_work"));
				acc.Language = reader["language"].ToString();

				return acc;
			}

			/// <summary>
			/// Get the amount of megabytes a user have already uploaded
			/// </summary>
			/// <param name="id"></param>
			/// <returns></returns>
			public double GetUsersUploadedMB(string id) {
				StringBuilder str = new StringBuilder();

				str.Append("SELECT * ");
				str.Append("FROM [dbo].[tbl_upload_log] ");
				str.Append("WHERE [user_pkid] = '" + id + "' ");
				str.Append("AND MONTH([month]) = '" + DateTime.Now.Month.ToString() + "'");

				DataSet data = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(data.Tables[0].Rows.Count > 0) {
					DataTableReader r = data.CreateDataReader();
					r.Read();

					return Convert.ToDouble(r.GetDecimal(r.GetOrdinal("uploaded")));
				}
				else {
					return 0.0;
				}
			}

			/// <summary>
			/// Count the upload log
			/// </summary>
			/// <param name="id"></param>
			/// <param name="mb"></param>
			public void CountUserUploadedMB(string id, double mb) {
				int res = 0;
				StringBuilder str = new StringBuilder();

				str.Append("SELECT * ");
				str.Append("FROM [dbo].[tbl_upload_log] ");
				str.Append("WHERE [user_pkid] = '" + id + "' ");
				//str.Append("AND MONTH([month]) = '" + DateTime.Now.Month.ToString() + "'");

				DataSet data = base.DBBaseClass.ExecuteQuery(str.ToString());

				if(data.Tables[0].Rows.Count > 0) {
					DataTableReader reader = data.CreateDataReader();
					reader.Read();

					int month = DateTime.Now.Month;

					double amount = Convert.ToDouble(reader.GetDecimal(reader.GetOrdinal("uploaded")));
					DateTime dt = reader.GetDateTime(reader.GetOrdinal("month"));

					amount = amount + Math.Round(mb, 3);

					DataRow row = data.Tables[0].Rows[0];

					if(month > dt.Month) {
						row["month"] = DateTime.Now;
						row["uploaded"] = Math.Round(mb, 3);
					}
					else {
						row["uploaded"] = amount;
					}

					res = base.DBBaseClass.ExecuteUpdate(data, "tbl_upload_log");
				}
				else {
					DataRow row = data.Tables[0].NewRow();

					row["pkid"] = Guid.NewGuid().ToString();
					row["user_pkid"] = id;
					row["uploaded"] = Convert.ToDecimal(mb);
					row["month"] = DateTime.Now;

					data.Tables[0].Rows.Add(row);

					res = base.DBBaseClass.ExecuteUpdate(data, "tbl_upload_log");
				}
			}

			/// <summary>
			/// Set upgrade in work
			/// </summary>
			/// <param name="id"></param>
			public void SetUpgradeInWork(string id, int produration) {
				Account acc = this.GetAccount(id, GetAccountType.ByID);
				StringBuilder str = new StringBuilder();

				str.Append("UPDATE [dbo].[tbl_user]");
				str.Append(" SET [upgrade_in_work] = " + (acc.UpgradeIsInWork ? 0 : 1) + ", ");
				str.Append(" [pro_duration] = '" + produration.ToString() + "' ");
				str.Append(" WHERE [pkid] = '" + id + "'");

				int iRes = base.DBBaseClass.ExecuteNonQuery(str.ToString());
			}

			/// <summary>
			/// Enable the pro account
			/// </summary>
			/// <param name="id"></param>
			/// <param name="produration"></param>
			public void EnableProAccount(string id, int produration) {
				DataSet data = base.GetUser(id);
				Account acc = this.GetAccount(id, GetAccountType.ByID);

				if(data.Tables[0].Rows.Count > 0) {
					DataRow row = data.Tables[0].Rows[0];

					if(acc.UpgradeIsInWork && acc.Type == 0) {
						row["upgrade_in_work"] = 0;
						row["group_pkid"] = "0fcb1bec-b966-480d-b9cc-855955c528d0";
						row["pro_start_date"] = DateTime.Now;
						row["pro_duration"] = produration;
					}
					else {
						row["upgrade_in_work"] = 0;
						row["group_pkid"] = "178efc30-5a67-472f-a1e2-e0f0f97f1c97";
						row["pro_start_date"] = DBNull.Value;
						row["pro_duration"] = DBNull.Value;
					}

					int iResult = base.DBBaseClass.ExecuteUpdate(data, "tbl_user");
				}
			}

			// ---------------------------------------------------------
			// PRIVATE MEMBERS
			// ---------------------------------------------------------

			/// <summary>
			/// Fill a account settings container including the user id
			/// </summary>
			/// <param name="reader"></param>
			/// <param name="userid"></param>
			/// <returns></returns>
			private AccountSettings _FillAccountSettingsFromTableReader(DataTableReader reader, string userid) {
				AccountSettings accs = new AccountSettings();

				accs.UserID = userid;

				try {
					if(reader != null) {
						accs.ID = reader["pkid"].ToString();
						accs.ImageListLayout = (ImageListLayout)reader.GetInt32(reader.GetOrdinal("imagelist_layout"));
					}
				}
				catch(Exception ex) {
					string s = ex.Message;
				}

				return accs;
			}
		}
	}
}
